package com.tsinghuabigdata.edu.ddmath.module.login.view;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.mobsandgeeks.saripaar.annotation.Pattern;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.ResultInfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.fragment.MyBaseFragment;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginSuccessHandler;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.KeyboardUtil;
import com.tsinghuabigdata.edu.ddmath.util.ValidatorUtils;
import com.tsinghuabigdata.edu.ddmath.view.FragmentActionbarView;
import com.tsinghuabigdata.edu.ddmath.view.GenderSelectorView;
import com.tsinghuabigdata.edu.utils.SetTimeout;

import java.util.List;
import java.util.concurrent.TimeUnit;

import roboguice.inject.InjectView;


/**
 * 注册
 * Created by Administrator on 2016/12/14.
 */

public class RegisterFragment extends MyBaseFragment implements View.OnClickListener {
    private static final String TAG = "RegisterFragment";
    private View root;
    private Button btRegister;
    private Button btLogin;

    @InjectView(R.id.genderview)
    private GenderSelectorView genderSelectorView;

    @Order(4)
    @NotEmpty(trim = true, message = "昵称不能为空", sequence = 1)
    @InjectView(R.id.et_nickname)
    private EditText etNickname;

    @Order(1)
    @NotEmpty(trim = true, message = "手机号不能为空", sequence = 1)
    @Pattern(regex = ValidatorUtils.MOBILE_REGEX, message = "请输入正确手机号", sequence = 2)
    @InjectView(R.id.et_phone)
    private EditText etPhone;

    @Order(3)
    @NotEmpty(trim = true, message = "密码不能为空", sequence = 1)
    @Password(message = "密码最少6位，请重新输入", min = 6, sequence = 2)
    @InjectView(R.id.et_passwd)
    private EditText etPasswd;

    @Order(2)
    @NotEmpty(trim = true, message = "验证码不能为空", sequence = 1)
    @InjectView(R.id.et_verifycode)
    private EditText etVerifycode;

    @InjectView(R.id.bt_verifycode)
    private Button btVerifycode;

    private FragmentActionbarView fragmentActionbarView;

    private Validator mValidator;

    private ProgressDialog progressDialog;

    private SetTimeout mSetTimeout;
    private boolean isTimeCountStop;
    private final int mMaxTime = AppConst.CODE_MAX_TIME;

    private String mAccessToken;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_register, container, false);
        return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
        initValidator();
    }

    private void initValidator() {
        mValidator = new Validator(this);
        mValidator.setValidationListener(new Validator.ValidationListener() {
            @Override
            public void onValidationSucceeded() {
                KeyboardUtil.hidInput(getActivity());
                if (!ValidatorUtils.validateMobile(etPhone.getText().toString().trim())) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                //全部验证完输入，开始注册
                register();
            }

            @Override
            public void onValidationFailed(List<ValidationError> errors) {
                for (ValidationError error : errors) {
                    ((EditText) error.getView()).setError(error.getFailedRules().get(0).getMessage(getContext()));
                }
            }
        });
    }

    private void initView() {
        btRegister = (Button) root.findViewById(R.id.bt_register);
        btLogin = (Button) root.findViewById(R.id.bt_login);

        fragmentActionbarView = (FragmentActionbarView) root.findViewById(R.id.fr_actionbar);
        fragmentActionbarView.setLeftTitle("取消");
        fragmentActionbarView.setTitle("注册");

        //actionbar listener
        View.OnClickListener actionbarListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.left_icon:
                    case R.id.bar_left_btn:
//                        AlertManager.toast(getActivity(), "left");
                        finish();
                        break;
                    case R.id.right_icon:
                    case R.id.bar_right_btn:
                        break;
                }
            }
        };
        fragmentActionbarView.setListener(actionbarListener);

        //listener
        btRegister.setOnClickListener(this);
        btLogin.setOnClickListener(this);
        btVerifycode.setOnClickListener(this);

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    AlertManager.toast(getContext(), "onkeylistener ");
                    return true;
                }
                return false;
            }
        });
    }

    private void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_register:
                mValidator.validate();
                break;
            case R.id.bt_login:
//                AlertManager.toast(getContext(), genderSelectorView.getSelGender() == GenderSelectorView.GIRL ? "girl" : "boy");
                finish();
                goFragment(new LoginFragment());
                break;
            case R.id.bt_verifycode:
                checkPhoneUsed();
                break;
        }
    }

    private void register() {
        String nickname = etNickname.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String passwd = etPasswd.getText().toString().trim();
        String sex = genderSelectorView.getSelGender() == GenderSelectorView.GIRL ? "female" : "male";
        String validcode = etVerifycode.getText().toString().trim();
        progressDialog.setMessage("注册中...");
        progressDialog.show();
        new LoginModel().register(nickname, phone, passwd, sex, validcode, new RequestListener<String>() {
            @Override
            public void onSuccess(String accountId) {
                progressDialog.dismiss();
                AlertManager.toast(getContext(), "注册成功");
                //注册成功后，自动登录一次
                autologin();
                //进入完善个人信息界面
//                finish();
//                goFragment(new UserInfoSuplementFragment());
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                AlertManager.showErrorInfo(getContext(), ex);
//                goFragment(new UserInfoSuplementFragment());//// TODO: 2017/2/18

            }
        });
    }

    private void autologin() {
        final String loginName = etPhone.getText().toString().trim();
        final String passwd = etPasswd.getText().toString().trim();
        new LoginModel().login(getContext(), loginName, passwd, new RequestListener<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                if (loginInfo == null) {
//                    AlertManager.toast(getContext(), "用户名或密码错误");
                    //跳到登录页面
                    finish();
                    goFragment(new LoginFragment());
                } else {
                    LoginSuccessHandler.loginSuccessHandler(getContext(), loginName, passwd);
                    finish();
                    goFragment(new UserInfoSuplementFragment());
                }
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                finish();
                //跳到登录页面
                goFragment(new LoginFragment());
            }
        });
    }

    private void checkPhoneUsed() {
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            etPhone.setError("手机号不能为空");
            return;
        } else if (!ValidatorUtils.validateMobile(phone)) {
            etPhone.setError("请输入正确手机号");
            return;
        }
        //start get verifycode from server
        progressDialog.setMessage("手机号校验中...");
        progressDialog.show();
        new LoginModel().isPhoneUsed(phone, new RequestListener<ResultInfo>() {
            @Override
            public void onSuccess(ResultInfo res) {
                progressDialog.dismiss();
                if (res != null && res.getMessage().equals("have used")) {
                    AlertManager.toast(getContext(), "该号码已注册，请登录");
                    finish();
                    goFragment(new LoginFragment());
                } else {
                    sendVerifycode();
                }
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                AlertManager.showErrorInfo(getContext(), ex);
            }
        });
    }

    private void sendVerifycode() {
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            etPhone.setError("手机号不能为空");
            return;
        } else if (!ValidatorUtils.validateMobile(phone)) {
            etPhone.setError("请输入正确手机号");
            return;
        }
        //start get verifycode from server
        progressDialog.setMessage("获取验证码...");
        progressDialog.show();
        String type = "register"; //操作类型(register, passwdRetrieve,binding)
        new LoginModel().getVerifycode(phone, type, new RequestListener<String>() {
            @Override
            public void onSuccess(String res) {
                progressDialog.dismiss();
                AlertManager.toast(getContext(), "验证码已发送至手机，请查看");
                getVerifycodeSuccess();
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                if (response.getCode() == 21110) {
                    AlertManager.toast(getContext(), "手机已被注册");
                } else {
                    AlertManager.showErrorInfo(getContext(), ex);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSetTimeout != null) {
            Log.d("recover", "onDestroy: ");
            isTimeCountStop = true;
            mSetTimeout.cancel();
        }
    }

    private void getVerifycodeSuccess() {
        btVerifycode.setEnabled(false);
        btVerifycode.setText(mMaxTime + getString(R.string.resend_verifycode));

        mSetTimeout = new SetTimeout(mMaxTime, TimeUnit.SECONDS, 1);
        mSetTimeout.setHandler(new SetTimeout.SetTimeoutHandler() {
            @Override
            public void handler(final int current) {
                if (isTimeCountStop) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int remain = mMaxTime - current - 1;
                        if (remain > 0) {
                            btVerifycode.setText(remain + getString(R.string.resend_verifycode));
                        } else {
                            btVerifycode.setText(getText(R.string.send_verifycode));
                            btVerifycode.setEnabled(true);
                        }
                    }
                });
            }
        });
        mSetTimeout.start();
    }
}
